package org.qiyu.live.im.core.server.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-10-05
 * Time: 23:27
 */
public class BioServer2 {
    // 搞一个线程池
    static ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(10, 10, 3, TimeUnit.MINUTES, new ArrayBlockingQueue<>(1000));
    public static void main(String[] args) throws IOException {
        // 创建服务端socket
        ServerSocket serverSocket = new ServerSocket();
        // 绑定9090端口,监听9090端口
        serverSocket.bind(new InetSocketAddress(9090));
        // 阻塞获取数据
        System.out.println("server开始监听9090端口");
        while (true) {
            Socket socket = serverSocket.accept();// 这里是BIO会进行阻塞
            // 每次接收一个连接就交给线程池去执行(线程池开启一个异步线程去执行)
            poolExecutor.execute(() -> {
                // 不断地获取数据
                while (true) {
                    // 我们要把数据收进来-->输入流
                    InputStream inputStream = null;
                    try {
                        inputStream = socket.getInputStream();
                        byte[] bytes = new byte[10];
                        inputStream.read(bytes);
                        System.out.println("服务端接收数据为 : " + new String(bytes));
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }
}